package com.newlink.building.utils

import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.provider.Settings
import android.telephony.TelephonyManager
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory
import com.newlink.building.common_base.utils.NLog
import java.security.MessageDigest
import java.util.*

/**
 * 设备ID获取工具类
 * 提供多种设备标识符的获取方式，并提供兜底方案
 */
object NL_DeviceIdHelper {

    private const val PREFS_NAME = "device_id_prefs"
    private const val KEY_CACHED_DEVICE_ID = "cached_device_id"

    /**
     * 获取设备ID，优先级如下：
     * 1. 阿里云推送 DeviceId
     * 2. Android ID
     * 3. IMEI (需要权限，Android 10+已弃用)
     * 4. 生成并缓存的UUID
     */
    fun getDeviceId(context: Context): String {
        return try {
            // 1. 尝试获取阿里云推送的DeviceId
            val aliyunDeviceId = getAliyunDeviceId()
            if (aliyunDeviceId.isNotEmpty()) {
                NLog.e("[DeviceIdHelper] Using Aliyun DeviceId: $aliyunDeviceId")
                return aliyunDeviceId
            }

            // 2. 尝试获取Android ID
            val androidId = getAndroidId(context)
            if (androidId.isNotEmpty()) {
                NLog.e("[DeviceIdHelper] Using Android ID: $androidId")
                return androidId
            }

            // 3. 尝试获取IMEI（仅适用于有权限的设备）
            val imei = getIMEI(context)
            if (imei.isNotEmpty()) {
                NLog.e("[DeviceIdHelper] Using IMEI: ${imei.take(8)}***")
                return imei
            }

            // 4. 生成并缓存UUID作为兜底
            val cachedId = getCachedOrGenerateDeviceId(context)
            NLog.e("[DeviceIdHelper] Using cached/generated ID: $cachedId")
            cachedId
        } catch (e: Exception) {
            NLog.e("[DeviceIdHelper] Error getting device ID: ${e.message}")
            // 最后的兜底方案
            getCachedOrGenerateDeviceId(context)
        }
    }

    /**
     * 获取阿里云推送的DeviceId
     */
    private fun getAliyunDeviceId(): String {
        return try {
            val deviceId = PushServiceFactory.getCloudPushService()?.deviceId
            if (!deviceId.isNullOrEmpty()) {
                deviceId
            } else {
                ""
            }
        } catch (e: Exception) {
            NLog.e("[DeviceIdHelper] Failed to get Aliyun DeviceId: ${e.message}")
            ""
        }
    }

    /**
     * 获取Android ID
     */
    @SuppressLint("HardwareIds")
    private fun getAndroidId(context: Context): String {
        return try {
            val androidId = Settings.Secure.getString(
                context.contentResolver,
                Settings.Secure.ANDROID_ID
            )
            if (!androidId.isNullOrEmpty() && androidId != "9774d56d682e549c") {
                // 过滤掉已知的无效Android ID
                androidId
            } else {
                ""
            }
        } catch (e: Exception) {
            NLog.e("[DeviceIdHelper] Failed to get Android ID: ${e.message}")
            ""
        }
    }

    /**
     * 获取IMEI（需要权限，Android 10+已弃用）
     */
    @SuppressLint("HardwareIds", "MissingPermission")
    private fun getIMEI(context: Context): String {
        return try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                // Android 10+ 不再支持IMEI获取
                ""
            } else {
                val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as? TelephonyManager
                val imei = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    telephonyManager?.imei
                } else {
                    @Suppress("DEPRECATION")
                    telephonyManager?.deviceId
                }
                if (!imei.isNullOrEmpty()) imei else ""
            }
        } catch (e: Exception) {
            // 没有权限或其他异常
            ""
        }
    }

    /**
     * 获取缓存的设备ID或生成新的
     */
    private fun getCachedOrGenerateDeviceId(context: Context): String {
        val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
        var deviceId = prefs.getString(KEY_CACHED_DEVICE_ID, "")

        if (deviceId.isNullOrEmpty()) {
            // 生成基于设备信息的唯一ID
            deviceId = generateUniqueDeviceId(context)
            prefs.edit().putString(KEY_CACHED_DEVICE_ID, deviceId).apply()
            NLog.e("[DeviceIdHelper] Generated new device ID: $deviceId")
        }

        return deviceId
    }

    /**
     * 生成基于设备信息的唯一ID
     */
    private fun generateUniqueDeviceId(context: Context): String {
        val deviceInfo = StringBuilder().apply {
            append(Build.BOARD)
            append(Build.BRAND)
            append(Build.DEVICE)
            append(Build.HARDWARE)
            append(Build.ID)
            append(Build.MANUFACTURER)
            append(Build.MODEL)
            append(Build.PRODUCT)
            append(Build.SERIAL)
            append(Build.USER)
        }.toString()

        return try {
            val digest = MessageDigest.getInstance("MD5")
            val hash = digest.digest(deviceInfo.toByteArray())
            hash.joinToString("") { "%02x".format(it) }
        } catch (e: Exception) {
            // 如果MD5失败，使用UUID
            UUID.randomUUID().toString().replace("-", "")
        }
    }

    /**
     * 清除缓存的设备ID（用于调试）
     */
    fun clearCachedDeviceId(context: Context) {
        val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
        prefs.edit().remove(KEY_CACHED_DEVICE_ID).apply()
        NLog.e("[DeviceIdHelper] Cleared cached device ID")
    }

    /**
     * 获取设备信息用于调试
     */
    fun getDeviceInfo(context: Context): String {
        return """
            Device Info:
            - Aliyun DeviceId: ${getAliyunDeviceId()}
            - Android ID: ${getAndroidId(context)}
            - Model: ${Build.MODEL}
            - Manufacturer: ${Build.MANUFACTURER}
            - Android Version: ${Build.VERSION.RELEASE}
            - API Level: ${Build.VERSION.SDK_INT}
            - Is Emulator: ${isEmulator()}
        """.trimIndent()
    }

    /**
     * 判断是否为模拟器
     */
    fun isEmulator(): Boolean {
        return (
            Build.FINGERPRINT.startsWith("generic") ||
                Build.FINGERPRINT.startsWith("unknown") ||
                Build.MODEL.contains("google_sdk") ||
                Build.MODEL.contains("Emulator") ||
                Build.MODEL.contains("Android SDK built for x86") ||
                Build.MANUFACTURER.contains("Genymotion") ||
                Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic") ||
                "google_sdk" == Build.PRODUCT
            )
    }
}
